<template>
  <div class="process">
    <h2>商品审核</h2>
    <div class="search-container">
      <div class="box">
        <el-input class="el-input" v-model="searchQuery" placeholder="输入商品信息搜索" @keyup.enter="searchUsers"></el-input>
        <select class="el-input border" v-model="selectedCategory">
          <option value="">商品分类</option>
          <option v-for="(category, index) in uniqueGoodsSorts" :key="index" :value="category">{{ category }}</option>
        </select>
        <select class="el-input border" v-model="selectedSeller">
          <option value="">商家名称</option>
          <option v-for="(name, index) in nameGoodsSorts" :key="index" :value="name">{{ name }}</option>
        </select>
      </div>
      <div class="box">
        <div class="el-input">
          <input type="date" v-model="startTime" placeholder="开始时间">
          <span>--</span>
          <input type="date" v-model="endTime" placeholder="结束时间">
        </div>
        <select class="el-input border" v-model="selectedStatus">
          <option value="">审核状态</option>
          <option value="已通过">已通过</option>
          <option value="待审核">待审核</option>
          <option value="不通过">不通过</option>
        </select>
        <div style="display: flex;justify-content: center;width: 400px;">
          <button class="border color" @click="search">
            <img src="../../assets/icons/search-1.png" alt="">搜索
          </button>
          <button class="border" @click="reset">
            <img src="../../assets/icons/none.png" alt=""> 重置
          </button>
        </div>
      </div>
    </div>
    <div class="line-container">
      <h3>商品列表</h3>
      <el-button @click="deleteSelectedUsers" class="el-button remove">
        <img src="../../assets/icons/down.png" alt=""> 批量审核
      </el-button>
      <el-table :data="currentUsers" stripe ref="userTable">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="商品信息" width="200">
          <template slot-scope="scope">
            <img :src="scope.row.GoodsPicture" alt="" style="width: 60px; height: 60px;">
            <div class="right" style="position: absolute;left: 80px;top: 22px;">
              <p>{{ scope.row.GoodsNamegoods }}</p>
              <p>{{ scope.row.GoodsId }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="GoodsSort" label="商品分类"></el-table-column>
        <el-table-column prop="GoodsBrandgoods" label="商品品牌"></el-table-column>

        <el-table-column prop="GoodsPrice" label="商品价格"></el-table-column>
        <el-table-column label="商家名称" width="200">
          <template slot-scope="scope">
            <p>{{ scope.row.UserName }}</p>
            <p>{{ scope.row.email }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="GoodsTime" label="提交时间" width="220">
          <template slot-scope="scope">
            <div>
              {{ formatTime(scope.row.GoodsTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="GoodsProcess" label="商品状态">
          <template slot-scope="scope">
            <span :style="{
              backgroundColor: getGoodsProcessColor(scope.row.GoodsProcess),
              color: getGoodsProcessTextColor(scope.row.GoodsProcess),
              padding: '3px 5px', borderRadius: '3px'
            }">
              {{ scope.row.GoodsProcess }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <p style="color: blue;cursor: pointer;" @click="showDetailDialog(scope.row)">查看详情</p>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" title="查看详情">
      <div style="display: flex; justify-content: center;">
        <img :src="detail.GoodsPicture" alt="" style="width: 280px; height: 280px;">
        <div style="padding-left: 10px;">
          <div class="detail-row">
            <div class="detail-item">
              <p class="detail-label">商品名字</p>
              <p>{{ detail.GoodsNamegoods }}</p>
            </div>
            <div class="detail-item">
              <p class="detail-label">上架时间</p>
              <p>{{ formatTime(detail.GoodsTime) }}</p>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <p class="detail-label">商家名称</p>
              <p>{{ detail.UserName }}</p>
            </div>
            <div class="detail-item">
              <p class="detail-label">商品价格</p>
              <p>￥{{ detail.GoodsPrice }}</p>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <p class="detail-label">商品类型</p>
              <p>{{ detail.GoodsSort }}</p>
            </div>
          </div>
          <div class="detail-item">
            <p class="detail-label">商品描述</p>
            <p>{{ detail.GoodsDescription }}</p>
          </div>


        </div>
      </div>
      <div>
        <label class="detail-label" style="margin-top: 20px;">添加不通过的理由：</label>
        <div class="detail-row detail-main">
          <el-input v-model="remark" placeholder="请输入不通过的理由"></el-input>
          <el-button @click="sendRemark" class="send-button" style="margin-left: 10px;">发送</el-button>
        </div>
      </div>
      <div>
        <span class="detail-label">状态：</span>
        <el-select v-model="detail.GoodsProcess" placeholder="请选择状态">
          <el-option label="待审核" value="待审核"></el-option>
          <el-option label="已通过" value="已通过"></el-option>
          <el-option label="不通过" value="不通过"></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="close-button">关闭</el-button>
        <el-button @click="confirm" class="confirm-button">确认</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="deleteDialogVisible" title="批量审核" width="500px">
      <h3 style="margin:-20px 0 20px 0;font-size: 18px;">审核数量 ({{ reviewedCount }}/{{ totalToReview }})</h3>
      <div v-if="selectedUsers.length > 0" style="display: flex; justify-content: space-around;">
        <img :src="selectedUsers[currentIndex].GoodsPicture" alt="" style="width: 180px; height: 180px;">
        <div class="pop">
          <p>商品名称：{{ selectedUsers[currentIndex].GoodsNamegoods }}</p>
          <p>商品分类: {{ selectedUsers[currentIndex].GoodsSort }}</p>
          <p>商品价格: ￥{{ selectedUsers[currentIndex].GoodsPrice }}</p>
          <p>商品描述: {{ selectedUsers[currentIndex].GoodsDescription }}</p>
        </div>
      </div>
      <div style="margin-top: 20px;font-size: 16px;">
        <span style="font-size: 18px;margin-right: 20px;">状态:</span>
        <el-radio-group v-model="batchStatus">
          <el-radio :label="'已通过'">已通过</el-radio>
          <el-radio :label="'不通过'">不通过</el-radio>
        </el-radio-group>
      </div>
      <div v-if="batchStatus === '不通过'" style="margin-top: 20px;">
        <label>填写不通过的理由：</label>
        <el-input style="margin-top: 10px;" v-model="batchRemark" placeholder="请输入不通过的理由"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">关闭</el-button>
        <el-button @click="confirmBatchReview">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { Message } from 'element-ui';
import jq from "jquery"
export default {
  data() {
    return {
      users: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      totalUsers: 0,
      detail: {},
      dialogVisible: false,
      deleteDialogVisible: false,
      remark: '',
      selectedCategory: '',
      selectedSeller: '',
      startTime: '',
      endTime: '',
      selectedStatus: '',
      batchStatus: '',
      batchRemark: '',
      selectedUsers: [],
      currentIndex: 0,
      isBatchProcessing: false, // 标志位
      uniqueGoodsSorts: [],
      nameGoodsSorts: [],
    };
  },
  mounted() {
    this.getData()
    document.querySelectorAll('.el-input input, .el-input select').forEach(input => {
      input.addEventListener('focus', () => {
        input.style.outline = 'none';
        input.style.borderColor = '#e2e2e2';
      });
    });
  },
  computed: {
    currentUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      let filteredUsers = this.users.filter(user => {
        const isSearchMatch = user.GoodsNamegoods.includes(this.searchQuery) || String(user.GoodsId).includes(this.searchQuery);
        const isCategoryMatch = this.selectedCategory === '' || user.GoodsSort === this.selectedCategory;
        const isSellerMatch = this.selectedSeller === '' || user.UserName === this.selectedSeller;
        const isStartTimeMatch = this.startTime === '' || new Date(user.GoodsTime) >= new Date(this.startTime);
        const isEndTimeMatch = this.endTime === '' || new Date(user.GoodsTime) <= new Date(this.endTime);
        const isStatusMatch = this.selectedStatus === '' || user.GoodsProcess === this.selectedStatus;
        return isSearchMatch && isCategoryMatch && isSellerMatch && isStartTimeMatch && isEndTimeMatch && isStatusMatch;
      });
      return filteredUsers.slice(start, end);
    },
    totalToReview() {
      return this.selectedUsers.length;
    },
    reviewedCount() {
      return this.currentIndex + (this.batchStatus ? 1 : 0);
    }
  },
  methods: {
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    getData() {
      let _this = this
      jq.ajax({
        type: "get",
        url: "http://127.0.0.1:3000/getShopData",
        success(res) {
          if (res.data == "") {
            return
          } else {
            _this.users = res.data
            console.log('_this.users', _this.users)
            _this.uniqueGoodsSorts = [...new Set(res.data.map(item => item.GoodsSort))];
            _this.nameGoodsSorts = [...new Set(res.data.map(item => item.UserName))];
          }
        }
      })
    },
    updateGoodsStatus(goodsId, status, remark) {
      return new Promise((resolve, reject) => {
        const _this = this;
        jq.ajax({
          type: 'PUT',
          url: 'http://127.0.0.1:3000/goodsprocess',
          data: {
            GoodsId: goodsId,
            GoodsProcess: status,
            GoodsScope: '上架中',
            processRecord: remark
          },
          success(res) {
            if (res.status === 200) {
              Message.success('商品状态更新成功');
              _this.getData();
              resolve(res);
            } else {
              Message.error('更新失败，请重试');
              reject(res);
            }
          },
          error(err) {
            console.error('更新请求失败:', err);
            Message.error('网络请求失败');
            reject(err);
          }
        });
      });
    },
    search() {
      const filteredUsers = this.users.filter(user => {
        const isSearchMatch = user.GoodsNamegoods.includes(this.searchQuery) || String(user.GoodsId).includes(this.searchQuery);
        const isCategoryMatch = this.selectedCategory === '' || user.GoodsSort === this.selectedCategory;
        const isSellerMatch = this.selectedSeller === '' || user.UserName === this.selectedSeller;
        const isStartTimeMatch = this.startTime === '' || new Date(user.GoodsTime) >= new Date(this.startTime);
        const isEndTimeMatch = this.endTime === '' || new Date(user.GoodsTime) <= new Date(this.endTime);
        const isStatusMatch = this.selectedStatus === '' || user.GoodsProcess === this.selectedStatus;
        return isSearchMatch && isCategoryMatch && isSellerMatch && isStartTimeMatch && isEndTimeMatch && isStatusMatch;
      });
      this.totalUsers = filteredUsers.length;
      console.log('搜索条件：', {
        searchQuery: this.searchQuery,
        selectedCategory: this.selectedCategory,
        selectedSeller: this.selectedSeller,
        startTime: this.startTime,
        endTime: this.endTime,
        selectedStatus: this.selectedStatus
      });
    },
    reset() {
      this.searchQuery = '';
      this.selectedCategory = '';
      this.selectedSeller = '';
      this.startTime = '';
      this.endTime = '';
      this.selectedStatus = '';
    },
    sendRemark() {
      console.log('发送处理备注:', this.remark);
      Message.success('发送成功');
      this.remark = '';
    },
    searchUsers() {
      this.currentPage = 1;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    getGoodsProcessColor(GoodsProcess) {
      switch (GoodsProcess) {
        case '不通过':
          return '#FFE4E1 ';
        case '已通过':
          return '#E8F5E9 ';
        case '待审核':
          return '#fff1da';
        default:
          return 'transparent';
      }
    },
    getGoodsProcessTextColor(GoodsProcess) {
      switch (GoodsProcess) {
        case '不通过':
          return '#8B0000';
        case '已通过':
          return '#006400';
        case '待审核':
          return '#FF6347';
        default:
          return 'black';
      }
    },
    showDetailDialog(row) {
      if (row) {
        this.detail = row;
        this.dialogVisible = true;
      } else {
        console.error('传递的行数据row未定义');
      }
    },
    deleteSelectedUsers() {
      const selectedRows = this.$refs.userTable.selection;
      if (!selectedRows.length) {
        Message.info('请选择需要审核的商品');
        return;
      }
      this.selectedUsers = selectedRows.filter(row =>
        ['待审核', '不通过'].includes(row.GoodsProcess)
      );
      if (!this.selectedUsers.length) {
        Message.info('请选择待审核或不通过的商品');
        return;
      }
      this.currentIndex = 0;
      this.deleteDialogVisible = true;
    },
    confirmBatchReview() {
      if (this.batchStatus === '不通过' && !this.batchRemark) {
        Message.error('请输入不通过的理由');
        return;
      }
      const currentUser = this.selectedUsers[this.currentIndex];
      this.updateGoodsStatus(
        currentUser.GoodsId,
        this.batchStatus,
        this.batchRemark
      )
        .then(() => {
          // 确保 currentIndex 不超过数组长度
          if (this.currentIndex < this.selectedUsers.length - 1) {
            this.currentIndex++;
            this.batchStatus = '';
            this.batchRemark = '';
            Message.info('请点击确认继续审核下一个商品');
          } else {
            this.deleteDialogVisible = false;
            this.batchStatus = '';
            this.batchRemark = '';
            this.selectedUsers = [];
            this.currentIndex = 0;
          }
        })
        .catch(error => {
          console.error('更新商品状态失败', error);
          Message.error('批量审核操作异常，请检查网络或重试');
          // 发生错误时，回退索引并重置状态
          this.currentIndex = Math.max(0, this.currentIndex - 1);
          this.batchStatus = '';
          this.batchRemark = '';
        });
    },
    confirm() {
      const { GoodsId, GoodsProcess, processRecord } = this.detail;
      this.updateGoodsStatus(GoodsId, GoodsProcess, processRecord);
      this.dialogVisible = false;
    },
  },
  created() {
    this.totalUsers = this.users.length;
  }
}
</script>

<style lang="less" scoped>
.process {
  padding: 70px 20px 20px 230px;
  background-color: #F9FAFB;
  width: 100%;

  h2 {
    display: block;
    visibility: visible;
    margin-left: 10px;
  }

  .search-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    position: relative;
    margin: 20px 10px;
    width: 98%;

    .box {
      display: flex;
      justify-content: space-evenly;
      width: 100%;
      margin-top: 10px;

      button {
        width: 180px;
        margin: 16px;
        padding: 10px 50px;
        margin-left: 16px;
      }
    }

    select {
      margin-right: 10px;
    }

    .el-input {
      margin: 20px;
      width: 400px;
      height: 40px;
      padding-left: 20px;
      color: #5d5a5a;
      font-size: 16px;

      span {
        padding: 9px;
      }

      input {
        background-color: white;
        padding: 10px 26px;
        border-radius: 5px;
        border: 1px solid #e2e2e2;
        color: #5d5a5a;
      }
    }

    .border {
      border: 1px solid #e2e2e2;
      border-radius: 5px;
      background-color: transparent;
      font-size: 16px;

      img {
        position: relative;
        top: 3px;
        right: 2px;
        width: 16px;
        height: 16px;
      }
    }

    .color {
      background-color: #1f3ff1;
      color: white;
    }
  }

  .line-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    position: relative;
    margin: 20px 10px;
    width: 98%;

    h3 {
      display: block;
      padding: 30px 0 20px 20px;
    }

    .el-button {
      padding: 15px 20px;
      border-radius: 8px;

      img {
        position: relative;
        top: 2px;
        width: 15px;
        height: 15px;
      }
    }

    .remove {
      background-color: #1f3ff1;
      color: white;
      position: absolute;
      top: 15px;
      right: 25px;
    }
  }

  .pop {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

    p {
      font-size: 17px;
    }
  }

  .detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    width: 100%;
  }

  .detail-main {
    width: 90%;
  }

  .detail-item {
    flex: 1;
    margin-right: 10px;
  }

  .detail-label {
    display: block;
    color: rgb(160, 160, 160);
    margin-bottom: 5px;
    font-weight: normal;
  }

  .close-button {
    background-color: #f4f4f4;
    color: #666;
    border: 1px solid #ccc;
  }

  .send-button {
    background-color: #409eff;
    color: white;
    border: none;
  }

  .confirm-button {
    background-color: #27c24c;
    color: white;
    border: none;
  }

  .stats-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: 20px 10px;
  }

  .stat-item {
    width: calc(50% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-item-1 {
    width: calc(25% - 20px);
    margin-bottom: 20px;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    border: 1px solid #e9e8e8;
    background-color: white;
    border-radius: 5px;
    padding: 20px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .stat-change {
    color: green;
  }

  .increase {
    color: green;
  }

  .decrease {
    color: red;
  }

  .stat-tip {
    color: rgb(255, 115, 0);
  }
}
</style>